<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\VariantAttribute;
use App\Models\VariantAttributeValue;
use App\Models\ProductImage;

class ProductVariantSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        DB::transaction(function () {
            $this->createProducts();
            $this->assignProductsToCategories();
            
            $this->command->info('✅ 产品数据创建完成');
        });
    }

    /**
     * 创建产品
     */
    private function createProducts(): void
    {
        // 获取规格模板
        $phoneTemplate = \App\Models\SpecificationTemplate::where('slug', 'orange-phone-complete-specs')->first();
        
        $products = [
            // Orange Phone 15 Pro（多规格商品）
            [
                'name' => 'Orange Phone 15 Pro',
                'slug' => 'orange-phone-15-pro',
                'description' => '钛金属设计，O17 Pro 芯片，Action 按钮，USB-C。',
                'long_description' => "Orange Phone 15 Pro 以航空级钛金属打造，更轻盈、更坚固、更Pro。\n\n钛金属设计\nOrange Phone 15 Pro 采用坚固轻盈的航天级钛金属设计。钛金属具有出色的强度重量比，让 Orange Phone 15 Pro 成为迄今为止最轻盈的 Pro 机型。\n\nO17 Pro 芯片\n全新的 O17 Pro 芯片带来突破性的性能提升。6 核 CPU、6 核 GPU 和 16 核神经网络引擎，为图形密集型游戏和专业级创作提供强大动力。",
                'features' => [
                    '航空级钛金属设计，更轻盈更坚固',
                    'O17 Pro 芯片，性能提升高达 10%',
                    '4800万像素主摄像头系统',
                    'USB-C 接口，传输速度高达 10Gb/s',
                ],
                'meta_data' => [
                    'technical_specs' => [
                        ['category' => '显示屏', 'items' => [
                            ['name' => '屏幕尺寸', 'value' => '6.1 英寸'],
                            ['name' => '分辨率', 'value' => '2556 x 1179 像素'],
                        ]],
                        ['category' => '芯片', 'items' => [
                            ['name' => '芯片', 'value' => 'O17 Pro 芯片'],
                            ['name' => 'CPU', 'value' => '6 核'],
                        ]],
                    ]
                ],
                'price' => 7999,
                'category' => 'orange-phone',
                'template_id' => $phoneTemplate?->id,
                'variants' => [
                    ['color' => '深空黑色', 'storage' => '128GB', 'price' => 7999, 'stock' => 25],
                    ['color' => '自然钛色', 'storage' => '256GB', 'price' => 8999, 'stock' => 30],
                ]
            ],
            
            // Orange AirPods Pro（单规格商品）
            [
                'name' => 'Orange AirPods Pro',
                'slug' => 'orange-airpods-pro',
                'description' => '主动降噪无线耳机，空间音频，自适应透明模式。',
                'long_description' => "Orange AirPods Pro 采用全新的入耳式设计，配备主动降噪功能，让您专注于音乐、播客和通话。\n\n主动降噪\nOrange AirPods Pro 采用先进的主动降噪技术，能够持续监测和调整声音信号，为您营造沉浸式的聆听体验。\n\n自适应透明模式\n自适应透明模式让您能听到周围的声音，同时保持音乐播放。",
                'features' => [
                    '主动降噪技术',
                    '自适应透明模式',
                    '空间音频，动态头部追踪',
                    '最长6小时聆听时间',
                ],
                'meta_data' => [
                    'technical_specs' => [
                        '驱动单元' => '定制高振幅驱动单元',
                        '降噪' => '主动降噪',
                        '电池续航' => '最长6小时聆听时间',
                        '防水等级' => 'IPX4',
                    ]
                ],
                'sku' => 'ORANGEAIRPODSPRO',
                'price' => 1999,
                'compare_price' => 2299,
                'cost_price' => 1200,
                'stock_quantity' => 50,
                'low_stock_threshold' => 10,
                'weight' => 0.054,
                'brand' => 'Orange',
                'is_active' => true,
                'is_featured' => false,
                'product_type' => 'single',
                'published_at' => now(),
            ],
        ];

        foreach ($products as $productData) {
            $product = Product::updateOrCreate(
                ['slug' => $productData['slug']],
                [
                    'name' => $productData['name'],
                    'slug' => $productData['slug'],
                    'description' => $productData['description'],
                    'short_description' => $productData['description'],
                    'long_description' => $productData['long_description'] ?? null,
                    'features' => $productData['features'] ?? [],
                    'meta_data' => $productData['meta_data'] ?? [],
                    'sku' => $productData['sku'] ?? strtoupper(str_replace(['-', ' '], ['', ''], $productData['slug'])),
                    'price' => $productData['price'],
                    'compare_price' => $productData['compare_price'] ?? $productData['price'] + 1000,
                    'cost_price' => $productData['cost_price'] ?? null,
                    'stock_quantity' => $productData['stock_quantity'] ?? 100,
                    'low_stock_threshold' => $productData['low_stock_threshold'] ?? 10,
                    'weight' => $productData['weight'] ?? null,
                    'brand' => 'Orange',
                    'is_active' => true,
                    'is_featured' => $productData['is_featured'] ?? true,
                    'product_type' => empty($productData['variants']) ? 'single' : 'multi_variant',
                    'template_id' => $productData['template_id'] ?? null,
                    'published_at' => now(),
                ]
            );

            // 添加默认图片
            $this->addDefaultImage($product);

            // 创建变体（仅多规格商品）
            if (!empty($productData['variants'])) {
                $this->createVariants($product, $productData['variants']);
            }

            $this->command->info("✅ 创建了 {$product->name}");
        }
    }

    /**
     * 创建产品变体
     */
    private function createVariants(Product $product, array $variants): void
    {
        // 根据第一个变体确定属性
        $firstVariant = $variants[0];
        $attributes = [];

        foreach (array_keys($firstVariant) as $key) {
            if (!in_array($key, ['price', 'stock'])) {
                $attributes[] = $key;
            }
        }

        // 创建变体属性
        foreach ($attributes as $index => $attrName) {
            $options = array_unique(array_column($variants, $attrName));
            VariantAttribute::create([
                'product_id' => $product->id,
                'name' => $this->getAttributeDisplayName($attrName),
                'slug' => $attrName,
                'type' => $this->getAttributeType($attrName),
                'options' => $options,
                'is_required' => true,
                'is_variant' => true,
                'sort_order' => $index + 1,
            ]);
        }

        // 创建变体
        foreach ($variants as $index => $variant) {
            $variantData = [
                'product_id' => $product->id,
                'sku' => $product->sku . '-' . ($index + 1),
                'name' => implode(' ', array_filter($variant, function($key) {
                    return !in_array($key, ['price', 'stock']);
                }, ARRAY_FILTER_USE_KEY)),
                'price' => $variant['price'],
                'compare_price' => $variant['price'] + 1000,
                'stock_quantity' => $variant['stock'],
                'attributes' => array_filter($variant, function($key) {
                    return !in_array($key, ['price', 'stock']);
                }, ARRAY_FILTER_USE_KEY),
                'is_active' => true,
                'is_default' => $index === 0,
                'sort_order' => $index,
            ];

            $productVariant = ProductVariant::create($variantData);

            // 创建属性值记录
            foreach ($attributes as $attrIndex => $attrName) {
                if (isset($variant[$attrName])) {
                    $attribute = VariantAttribute::where('product_id', $product->id)
                        ->where('slug', $attrName)
                        ->first();
                    
                    if ($attribute) {
                        VariantAttributeValue::create([
                            'variant_id' => $productVariant->id,
                            'attribute_id' => $attribute->id,
                            'value' => $variant[$attrName],
                            'display_value' => $variant[$attrName],
                            'sort_order' => $attrIndex + 1,
                        ]);
                    }
                }
            }
        }
    }

    /**
     * 添加默认图片
     */
    private function addDefaultImage(Product $product): void
    {
        ProductImage::create([
            'product_id' => $product->id,
            'image_path' => '/images/product-placeholder.svg',
            'is_primary' => true,
            'sort_order' => 1,
        ]);
    }

    /**
     * 分配产品到分类
     */
    private function assignProductsToCategories(): void
    {
        $categories = \App\Models\Category::all()->keyBy('slug');
        $products = Product::all();

        foreach ($products as $product) {
            $categorySlug = $this->getProductCategory($product->slug);
            if (isset($categories[$categorySlug])) {
                $product->categories()->syncWithoutDetaching([
                    $categories[$categorySlug]->id => [
                        'is_primary' => true,
                        'sort_order' => 1
                    ]
                ]);
                $this->command->info("✅ 关联 {$product->name} 到分类 {$categorySlug}");
            }
        }
    }

    /**
     * 获取产品分类
     */
    private function getProductCategory(string $slug): string
    {
        if (str_contains($slug, 'phone')) return 'orange-phone';
        if (str_contains($slug, 'book')) return 'orange-book';
        if (str_contains($slug, 'pods')) return 'accessories';
        return 'accessories';
    }

    /**
     * 获取属性显示名称
     */
    private function getAttributeDisplayName(string $attrName): string
    {
        return match($attrName) {
            'color' => '颜色',
            'storage' => '存储容量',
            'chip' => '芯片',
            'memory' => '内存',
            default => $attrName
        };
    }

    /**
     * 获取属性类型
     */
    private function getAttributeType(string $attrName): string
    {
        return match($attrName) {
            'color' => 'color',
            default => 'select'
        };
    }
}
